package code.rocky.guardedSuspension;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 依次存放请求的类
 */
public class RequestQueue {
    private final Queue<Request> queue = new LinkedList<Request>();

    /**
     * 1. 施加守护条件进行保护
     * 2. 不等待和等待的情况
     * 3. 执行 wait, 等待条件发生变化 [明确线程在等待什么?应该何时执行notify/notifyAll]
     * 4. 执行到while的下一条语句时一定能确定的事情
     * @return
     */
    public synchronized Request getRequest() {
        while (queue.peek() == null) { // 守护条件的逻辑非运算
            try {
                System.out.println(Thread.currentThread().getName() + ": wait() begins, queue = " + queue);
                wait();
                System.out.println(Thread.currentThread().getName() + ": wait() ends,   queue = " + queue);
            } catch (InterruptedException e) {
            }
        }
        // != null 守护条件
        return queue.remove();
    }

    public synchronized void putRequest(Request request) {
        queue.offer(request);
        System.out.println(Thread.currentThread().getName() + ": notifyAll() begins, queue = " + queue);
        notifyAll();
        System.out.println(Thread.currentThread().getName() + ": notifyAll() ends, queue = " + queue);
    }
}

